package com.lilosoft.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
	
	@Bean
    @ConditionalOnMissingBean(name="redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        // 设置值（value）的序列化采用GenericJackson2JsonRedisSerializer
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // 设置键（key）的序列化采用StringRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    
    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
	
    //===以下是基于JedisPool客户端访问单机redis服务===//
//	@Bean(name= "jedis.pool")
//	
//	@Autowired
//	public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config, 
//				@Value("${jedis.pool.host}")String host, 
//				@Value("${jedis.pool.port}")int port) {
//		return new JedisPool(config, host, port);
//	}
//	
//	@Bean(name= "jedis.pool.config")
//	public JedisPoolConfig jedisPoolConfig () {
//		JedisPoolConfig config = new JedisPoolConfig();
//		config.setMaxTotal(5000);
//		config.setMaxIdle(100);
//		config.setMaxWaitMillis(1000);
//		return config;
//	}
    
}
